<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import { useApplyUpdateNum } from '@fl/api/add-elevator-api'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'

const props = withDefaults(defineProps<{
    detail?: any
    modelValue: boolean
}>(), {
    detail: () => { },
})
const visible = defineModel<boolean>('visible', { required: true })
const { detail } = toRefs(props)

const formRef = ref()
const title = ref('设置加梯部数')

const initialState = {
    num: 0,
}
const state = ref(cloneDeep(initialState))

watchEffect(() => {
    if (detail.value) {
        state.value.num = detail.value.num
    }
})

// 提交表单
const { isPending, mutate } = useApplyUpdateNum()

// 提交
async function submit() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const params = {
            ...unref(detail),
            num: state.value.num,
        }
        console.log('params', params)
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                reset()
            },
        })
    }
}

function cancel() {
    reset()
}

function reset() {
    visible.value = false
    state.value = cloneDeep(initialState)
    formRef.value.formInstance.resetFields()
}

const columns: PlusColumn[] = [
    {
        fieldProps: { min: 0, max: 9, precision: 0, maxlength: 1 },
        label: '数量',
        prop: 'num',
        valueType: 'input-number',
    },
]

const rules = {
    num: [
        {
            message: '请输入数量',
            required: true,
        },
    ],
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="500"
                close-on-press-escape
                :has-footer="false"
                @cancel="cancel"
                @closed="reset"
    >
        <div class="mt-20">
            <PlusForm ref="formRef"
                      v-model="state"
                      :columns="columns"
                      :label-width="120"
                      :rules="rules"
                      :has-footer="false"
                      :row-props="{ gutter: 20 }"
            />
        </div>

        <div class="mx-auto mt20 flex justify-center">
            <el-button @click="cancel">
                取消
            </el-button>

            <SubmitBtn type="primary"
                       :loading="isPending"
                       @click="submit"
            >
                提交
            </SubmitBtn>
        </div>
    </PlusDialog>
</template>

<style lang="scss" scoped>

</style>
